package com.hsj.goldstore.base;

import android.content.Context;
import android.support.v4.content.Loader;


/**
 * Created by Administrator on 2018/3/21.
 */

public class PresenterLoader<P extends IPresenter> extends Loader<P> {
    private final PresenterFactory<P> factory;
    private P presenter;

    /**
     * @param context
     * @param factory 用于创建Presenter
     */
    public PresenterLoader(Context context, PresenterFactory<P> factory) {
        super(context);
        this.factory = factory;
    }

    /**
     * 在Activity的onStart()调用之后
     */
    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        if (presenter != null) {
            //将presenter传递给Acitivity/fragment
            deliverResult(presenter);
            return;
        }
        forceLoad();
    }

    /**
     * 在调用forceLoad()方法后自动调用，在这个方法中创建Presenter并返回它。
     */
    @Override
    protected void onForceLoad() {
        presenter = factory.create();
        deliverResult(presenter);
    }

    /**
     * 会在Loader被销毁之前调用，回收Presenter
     */
    @Override
    protected void onReset() {
        presenter = null;
    }
}
